/*package com.ultrasoft.farmasoft.repository;

public class LocalityDaoImpl {

}*/
package com.ultrasoft.farmasoft.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.ultrasoft.farmasoft.domain.Locality;

@Transactional(readOnly = false)
@Repository(value = "localityDao")
public class LocalityDaoImpl implements LocalityDao {
	private EntityManager em = null;
    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }
    
	public List<Locality> getLocality() {		
		TypedQuery<Locality> q = em.createNamedQuery("Locality.findAll",Locality.class);
		q.setParameter("active",true);
    	return q.getResultList();
	}
	public List<Locality> getLocalityListByRegionIdByActive(Integer regionId,boolean active){    	
    	TypedQuery<Locality> q = em.createNamedQuery("Locality.findByRegionIdByActive",Locality.class);
    	q.setParameter("regionId",regionId);
    	q.setParameter("active",active);
    	return q.getResultList();
	}
	public void add(Locality locality){
		em.persist(locality);
	}
	public void update(Locality locality) {
		em.merge(locality);
	}
	public void remove(Locality locality){
		Query q= em.createNamedQuery("Locality.deleteByLocalityIdByRegionId");
		q.setParameter("localityId",locality.getLocalityPK().getLocalityId());
		q.setParameter("regionId", locality.getLocalityPK().getRegionId());
		q.executeUpdate();	
	}
	public Locality findLocalityByRegionIdByLocalityId(Integer regionId ,Short localityId) {
		Locality res = null;
    	Query  q = em.createNamedQuery("Locality.findByRegionIdBylocalityId");
    	q.setParameter("regionId",regionId);
    	q.setParameter("localityId",localityId);
    	if(q.getResultList().size()==1)
    		res=(Locality)q.getSingleResult();
    	return res;
	}
	
	/*return IdLocalityMax and increment in one*/
	public short getLocalityIdMax(Integer regionId){
		short res = 0;
		try {
			Query  q = em.createNamedQuery("Locality.findByIdMaxLocality");
	    	q.setParameter("regionId",regionId);
	    	res = (Short)q.getSingleResult();
	    	res++;
		} catch (Exception e) {
			res=1;
		}
		return res;
	}

}

